package com.example.simpleforum.servlet;

import com.example.simpleforum.dao.ReplyDao;
import com.example.simpleforum.model.Reply;
import com.example.simpleforum.model.User;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Timestamp;

/**
 * 添加回复Servlet
 */
public class ReplyAddServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 获取当前登录用户
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        
        if (user == null) {
            // 用户未登录，重定向到登录页面
            response.sendRedirect(request.getContextPath() + "/login.jsp");
            return;
        }
        
        // 获取表单数据
        String postIdStr = request.getParameter("postId");
        String content = request.getParameter("content");
        
        // 表单验证
        if (postIdStr == null || postIdStr.trim().isEmpty()) {
            // 帖子ID为空，重定向到帖子列表页面
            response.sendRedirect(request.getContextPath() + "/PostListServlet");
            return;
        }
        
        if (content == null || content.trim().isEmpty()) {
            // 回复内容为空，重定向回帖子详情页面
            response.sendRedirect(request.getContextPath() + "/PostDetailServlet?id=" + postIdStr);
            return;
        }
        
        try {
            int postId = Integer.parseInt(postIdStr);
            
            // 创建回复对象
            Reply reply = new Reply();
            reply.setContent(content);
            reply.setUserId(user.getId());
            reply.setPostId(postId);
            reply.setCreateTime(new Timestamp(System.currentTimeMillis()));
            reply.setUpdateTime(reply.getCreateTime());
            
            // 保存回复
            ReplyDao replyDao = new ReplyDao();
            int replyId = replyDao.addReply(reply);
            
            if (replyId > 0) {
                // 回复成功，重定向回帖子详情页面
                response.sendRedirect(request.getContextPath() + "/PostDetailServlet?id=" + postId);
            } else {
                // 回复失败
                response.sendRedirect(request.getContextPath() + "/PostDetailServlet?id=" + postId + "&error=reply_failed");
            }
        } catch (NumberFormatException e) {
            // 帖子ID格式错误，重定向到帖子列表页面
            response.sendRedirect(request.getContextPath() + "/PostListServlet");
        }
    }
}